#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define NUM 1024

namespace Client
{
    class TcpClient
    {
    public:
        TcpClient(const std::string &ip, const uint16_t &port)
            : _sock(-1), _serverip(ip), _serverport(port)
        {
        }
        void initClinet()
        {
            // 1.创建socket套接字
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                std::cerr << "create socket error!" << std::endl;
                exit(2);
            }
        }
        void start()
        {
            // 2.发起连接
            struct sockaddr_in server;
            server.sin_family = AF_INET;
            server.sin_port = htons(_serverport);
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                std::cerr << "socket connect error!" << std::endl;
            }
            else
            {
                std::string message;
                while (true)
                {
                    std::cout << "Please Enter# ";
                    std::getline(std::cin, message);
                    write(_sock, message.c_str(), message.size());

                    char buffer[NUM];
                    size_t s = read(_sock, buffer, sizeof(buffer) - 1);
                    if (s > 0)
                    {
                        std::cout << "Server回显# " << buffer << std::endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~TcpClient()
        {
            if (_sock >= 0)
            {
                close(_sock);
            }
        }

    private:
        int _sock;
        std::string _serverip;
        uint16_t _serverport;
    };
}